﻿//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.Windows.Controls.Primitives;
using P2.Cuberry.Framework.Helper;


namespace P2.Cuberry.Modules.SimpleAccounting.HRPayroll
{

    // Interaction logic for HRPayrollsDetailView.xaml
    public partial class HRPayrollsDetailsView : Window, IHRPayrollsDetailsView
    {
        public HRPayrollsDetailsView()
        {
            InitializeComponent();
        }

        public HRPayrollsDetailsPresentationModel Model
        {
            get { return this.DataContext as HRPayrollsDetailsPresentationModel; }
            set
            {
                if (value != null)
                {
                    this.DataContext = value;                 
                }
            }
        }


        private void PrintBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string myReportLocation = P2.Cuberry.Framework.Helper.Configuration.ConfigurationSetUp.GetAppConfigValue("ReportLocation") + @"PrintHRPayrollsDetails" + P2Translator.CultureLanguageFU + ".rdlc";

                SortedList myDataSourceCollection = new SortedList();
                myDataSourceCollection.Add("HRPayroll", this.Model.Model);
                
                myDataSourceCollection.Add("PayrollItem", this.Model.Model.PayrollItems);
                
                P2ReportViewer myReportViewer = new P2ReportViewer(myReportLocation, myDataSourceCollection, "Transaction Print");
                myReportViewer.Show();

            }
            catch (Exception ex) //AM:TC!!
            {
                ExceptionPolicy.HandleException(ex, "Default Policy");
                P2Validator.YellowErrorDialog.Confirm(P2Translator.GetResource("Report error"), ex.Message, null, null, null);
            }
        }
        

        private void AddPayrollItemBtn_Click(object sender, RoutedEventArgs e)
        {
            Model.EditTransactionItem(null);
        }


        public void CellFocusable(Object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Controls.DataGridRow dgrow = (System.Windows.Controls.DataGridRow)sender;
                DataGridCellsPresenter presenter = GeneralHelper.GetVisualChild<DataGridCellsPresenter>(dgrow);

                // try to get the cell but it may possibly be virtualized
                System.Windows.Controls.DataGridCell cell = (System.Windows.Controls.DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(0);
                if (cell == null)
                {
                    // now try to bring into view and retreive the cell
                    HRPayrollItemList.ScrollIntoView(dgrow, HRPayrollItemList.Columns[0]);
                    cell = (System.Windows.Controls.DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(0);
                }

                cell.Focus();
                ((System.Windows.Controls.DataGridRow)sender).Loaded -= CellFocusable;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        private void DeletePayrollItemBtn_Click(object sender, RoutedEventArgs e)
        {
            if (HRPayrollItemList.SelectedItem != null)
            {
                BusinessEntities.HRPayrollItem selectedItem = (BusinessEntities.HRPayrollItem)HRPayrollItemList.SelectedItem;
                Model.Model.PayrollItems.Remove(selectedItem);
            }
        }



        public BusinessEntities.HRPayrollItem SelectedPayrollItem
        {
            get
            {
                if (HRPayrollItemList.SelectedItem != null)
                {
                    return (BusinessEntities.HRPayrollItem)HRPayrollItemList.SelectedItem;
                }
                else
                    return null;
            }
        }


        
        public void UpdateFocusedControl()
        {
            try
            {
                TextBox focusedTextBox = Keyboard.FocusedElement as TextBox;
                if (focusedTextBox == null)
                    return;

                BindingExpression textBindingExpr =
                  focusedTextBox.GetBindingExpression(TextBox.TextProperty);
                if (textBindingExpr == null)
                    return;

                textBindingExpr.UpdateSource();
            }
            catch (Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }

        }


        private void HRPayrollItemList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (HRPayrollItemList.SelectedItem != null && (Model.Model.StatusID == 186001 || Model.Model.StatusID == 186004))
            {
                BusinessEntities.HRPayrollItem selectedItem = (BusinessEntities.HRPayrollItem)HRPayrollItemList.SelectedItem;
                Model.EditTransactionItem(selectedItem);
            }
        }


  
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.PaymentDescription.GetBindingExpression(TextBox.TextProperty).UpdateSource();
            this.PaymentNo.GetBindingExpression(TextBox.TextProperty).UpdateSource();
            this.PaymentDate.GetBindingExpression(System.Windows.Controls.DatePicker.SelectedDateProperty).UpdateSource();
           
        }


        public bool AskSave()
        {
            try
            {
                UpdateFocusedControl();

                if (!Model.IsReadOnly && Model.ModelIsModified)
                {
                    MessageBoxOptions opt = MessageBoxOptions.None;
                    if (this.FlowDirection == FlowDirection.RightToLeft) opt = MessageBoxOptions.RtlReading;
                    MessageBoxResult result = MessageBox.Show(P2Translator.GetResource("hrPayrollNotSaved"), P2Translator.GetResource("hrPayrollNotSavedCaption"), MessageBoxButton.YesNoCancel, MessageBoxImage.Exclamation, MessageBoxResult.Cancel, opt);

                    switch (result)
                    {
                        case MessageBoxResult.Cancel:
                            break;
                        case MessageBoxResult.No:
                            return true;

                        case MessageBoxResult.Yes:
                            Model.Save();
                            if (StatusStrip.Status == "green")
                                return true;
                            break;
                        default:
                            break;
                    }
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return false;
            }
        }


        public bool YellowStatusWarning(string MessageText, string CaptionText)
        {
            MessageBoxOptions opt = MessageBoxOptions.None;
            if (this.FlowDirection == FlowDirection.RightToLeft) opt = MessageBoxOptions.RtlReading;
            MessageBoxResult result = MessageBox.Show(MessageText, CaptionText, MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.Cancel, opt);

            switch (result)
            {
                case MessageBoxResult.Cancel:
                    break;
                case MessageBoxResult.No:
                    return false;
                    
                case MessageBoxResult.Yes:
                    return true;
                    
                default:
                    break;
            }
            return false;
        }


        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = !this.AskSave();
        }


    }
}
